package com.draw.cli.gui;

import java.awt.FlowLayout;
import java.net.MalformedURLException;
import java.util.concurrent.Semaphore;

import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.xml.ws.WebServiceException;

import com.draw.cli.gui.panel.Refreshable;
import com.draw.cli.webclient.GlobalClient;

public class StateBar extends JPanel implements Runnable, Refreshable {
	private static final long serialVersionUID = -6806436575540436148L;

	public static final String SERVER_ONLINE = "Serveur disponible.";
	public static final String SERVER_OFFLINE = "Problème de connection au serveur...";

	private static StateBar instance = new StateBar();

	public static StateBar getInstance() {
		return instance;
	}

	private JLabel info;
	private Thread thread;
	private Semaphore sem;

	public StateBar() {
		this.setBorder(BorderFactory.createLoweredBevelBorder());
		this.setLayout(new FlowLayout(FlowLayout.LEFT));
		this.add(MemoryBar.getInstance());
		this.info = new JLabel("En attente");
		this.add(this.info);

		this.sem = new Semaphore(1);
		this.thread = null;
		MemoryBar.getInstance().start();
		this.testConnection();
	}

	public void setText(String txt) {
		this.info.setText(txt);
	}

	public void testConnection() {
		if (this.thread == null) {
			this.thread = new Thread(this);
			this.thread.start();
		}
	}

	public void setServerOnline() {
		this.setText(SERVER_ONLINE);
	}

	public void setServerOffline() {
		this.setText(SERVER_OFFLINE);
	}

	@Override
	public void run() {
		try {
			this.sem.acquire();
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
		this.setText("Test de la connexion...");
		try {
			GlobalClient.getInstance();
			this.setServerOnline();
		} catch (MalformedURLException | WebServiceException e) {
			this.setServerOffline();
			// e.printStackTrace();
		}
		this.sem.release();
		this.thread = null;
	}

	@Override
	public void refresh() {
		this.testConnection();
	}
}
